<?php
header ('Content-type: text/html; charset=utf-8');
defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
defined('APP_PATH') ? null : define('APP_PATH', 'mcot_login' . DS . 'application');

require_once (APP_PATH . DS . 'initialize.php');

if (!$_SESSION['logged_in'])
{
    redirect_to('mcot_login/administrator/login.php');
} 

$strFileName = $_POST["wFile"];
$json = $_POST['content'];

//var_dump($strFileName);
//var_dump($json);

//Save on temp file.
$tempFileWrite = fopen("temp.json", 'w');

//Add blackslash infront of escape-character.
fwrite($tempFileWrite,  addslashes($json));
fclose($tempFileWrite);

//Open and read temp file.
$tempFileRead = fopen("temp.json", 'r');
$stringJson = '';
if ($tempFileRead) {
	while (!feof($tempFileRead)) {
		$temp = fgets($tempFileRead);

		$stringJson .= $temp;
	}

	fclose($tempFileRead);
}else{
	//Handle false
	echo "<script> alert('Save failure, please try again.');</script>";
}


// $objFopen = fopen($strFileName, 'w');
// if($objFopen){
	//Remove backslash.
	$tempString = (stripslashes ($stringJson));
	$removeTailArray =  str_replace(",]}", "]}", $tempString);
	$undefinedRemoved_head = str_replace(",undefined", "", $removeTailArray);
	$undefinedRemoved_tail = str_replace("undefined,", "", $undefinedRemoved_head);
// 	echo "<script> alert('".$tempString."');</script>";
// 	if(json_decode($tempString) != NULL){
		$objFopen = fopen($strFileName, 'w');
		if($objFopen){
			fwrite($objFopen, stripslashes($undefinedRemoved_tail));
			fclose($objFopen);
			//Success
			echo "<script> alert('Save successful.');</script>";
			echo "<script> window.location = 'index.php';</script>";
			//echo "<script> window.parent.location.reload();</script>";
		}else{
			//Handle false
			echo "<script> alert('Save failure, please try again.');</script>";
			//	echo '<script> history.back();</script>';
		}
		
// 	}else{
// 		//Handle false
// 		echo "<script> alert('Error!, incorrect JSON format.');</script>";
// 	}
	

?>